import React, { useEffect, useState } from 'react';
import { Form, Input, Button, Card, Typography, message, Checkbox, Row, Col } from 'antd';
import { UserOutlined, LockOutlined, LoadingOutlined, SafetyOutlined } from '@ant-design/icons';
import { useNavigate, useLocation } from 'react-router-dom';
import { useAppDispatch, useAppSelector } from '../../store';
import { login, selectLoginLoading, selectIsAuthenticated, clearError } from '../../store/slices/authSlice';
import { LoginRequest } from '../../types';
import Captcha from '../../components/Captcha';
import './Login.css';

const { Title, Text } = Typography;

const Login: React.FC = () => {
  const [form] = Form.useForm();
  const dispatch = useAppDispatch();
  const navigate = useNavigate();
  const location = useLocation();

  const loginLoading = useAppSelector(selectLoginLoading);
  const isAuthenticated = useAppSelector(selectIsAuthenticated);

  // 验证码相关状态
  const [captchaCode, setCaptchaCode] = useState('');
  const [showCaptcha, setShowCaptcha] = useState(false);
  const [loginAttempts, setLoginAttempts] = useState(0);

  // 如果已经登录，重定向到首页
  useEffect(() => {
    if (isAuthenticated) {
      const from = (location.state as any)?.from?.pathname || '/dashboard';
      navigate(from, { replace: true });
    }
  }, [isAuthenticated, navigate, location]);

  // 清除错误信息
  useEffect(() => {
    dispatch(clearError());
  }, [dispatch]);

  // 处理登录
  const handleLogin = async (values: LoginRequest & { captcha?: string }) => {
    try {
      // 如果显示验证码，验证验证码
      if (showCaptcha) {
        if (!values.captcha) {
          message.error('请输入验证码');
          return;
        }
        if (values.captcha.toLowerCase() !== captchaCode.toLowerCase()) {
          message.error('验证码错误');
          setLoginAttempts(prev => prev + 1);
          return;
        }
      }

      await dispatch(login({
        username: values.username,
        password: values.password
      })).unwrap();
      message.success('登录成功');

      // 重置登录尝试次数
      setLoginAttempts(0);
      setShowCaptcha(false);

      // 重定向到原来要访问的页面或首页
      const from = (location.state as any)?.from?.pathname || '/dashboard';
      navigate(from, { replace: true });
    } catch (error) {
      message.error(error as string);

      // 增加登录尝试次数，超过2次显示验证码
      const newAttempts = loginAttempts + 1;
      setLoginAttempts(newAttempts);
      if (newAttempts >= 2) {
        setShowCaptcha(true);
      }
    }
  };

  return (
    <div className="login-container" style={{
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
      minHeight: '100vh',
      width: '100vw',
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
      position: 'relative',
      overflow: 'hidden',
      margin: 0,
      padding: 0,
    }}>
      {/* 背景装饰元素 */}
      <div style={{
        position: 'absolute',
        top: '-50%',
        left: '-50%',
        width: '200%',
        height: '200%',
        background: 'radial-gradient(circle, rgba(255,255,255,0.1) 1px, transparent 1px)',
        backgroundSize: '50px 50px',
        animation: 'float 20s ease-in-out infinite',
      }} />

      {/* 左侧3D图标区域 */}
      <div className="login-left" style={{
        flex: '1 1 50%',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        color: 'white',
        padding: '40px 60px',
        minHeight: '100vh',
        animation: 'fadeInLeft 1s ease-out',
      }}>
        {/* 3D图标容器 */}
        <div style={{
          width: '380px',
          height: '260px',
          position: 'relative',
          marginBottom: '40px',
          perspective: '1200px',
        }}>
          {/* 主卡片 - 深紫色系 */}
          <div className="card-3d" style={{
            position: 'absolute',
            width: '320px',
            height: '200px',
            background: 'linear-gradient(145deg, #667eea, #764ba2)',
            borderRadius: '20px',
            border: '2px solid rgba(255,255,255,0.25)',
            transform: 'rotateY(-15deg) rotateX(10deg)',
            boxShadow: '0 30px 60px rgba(0,0,0,0.35), inset 0 2px 0 rgba(255,255,255,0.3)',
            left: '0',
            top: '0',
            transition: 'all 0.3s ease',
            overflow: 'hidden',
            animation: 'floatMain 3s ease-in-out infinite',
            cursor: 'pointer',
            zIndex: 3,
          }}>
            {/* 图表装饰 */}
            <div style={{
              position: 'absolute',
              top: '25px',
              left: '25px',
              right: '25px',
              height: '75px',
              background: 'rgba(255,255,255,0.25)',
              borderRadius: '12px',
              border: '1px solid rgba(255,255,255,0.3)',
              boxShadow: 'inset 0 2px 0 rgba(255,255,255,0.4)',
            }} />
            <div style={{
              position: 'absolute',
              bottom: '25px',
              left: '25px',
              right: '25px',
              height: '50px',
              background: 'rgba(255,255,255,0.15)',
              borderRadius: '8px',
              border: '1px solid rgba(255,255,255,0.2)',
              boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.3)',
            }} />
          </div>

          {/* 第二张卡片 - 中蓝色系 */}
          <div style={{
            position: 'absolute',
            width: '320px',
            height: '200px',
            background: 'linear-gradient(145deg, #4facfe, #667eea)',
            borderRadius: '20px',
            border: '2px solid rgba(255,255,255,0.2)',
            transform: 'rotateY(15deg) rotateX(5deg)',
            boxShadow: '0 25px 50px rgba(0,0,0,0.25), inset 0 2px 0 rgba(255,255,255,0.25)',
            right: '0',
            top: '25px',
            zIndex: 2,
            overflow: 'hidden',
            animation: 'floatSecondary 4s ease-in-out infinite',
          }} />

          {/* 第三张卡片 - 浅青色系 */}
          <div style={{
            position: 'absolute',
            width: '320px',
            height: '200px',
            background: 'linear-gradient(145deg, #a8edea, #4facfe)',
            borderRadius: '20px',
            border: '2px solid rgba(255,255,255,0.15)',
            transform: 'rotateY(-5deg) rotateX(2deg)',
            boxShadow: '0 20px 40px rgba(0,0,0,0.2), inset 0 2px 0 rgba(255,255,255,0.2)',
            left: '30px',
            top: '50px',
            zIndex: 1,
            overflow: 'hidden',
            animation: 'floatThird 5s ease-in-out infinite',
          }} />
        </div>

        <Title level={1} style={{
          color: 'white',
          marginBottom: '16px',
          fontSize: '36px',
          fontWeight: 'bold',
          textShadow: '0 2px 4px rgba(0,0,0,0.3)',
        }}>
          欢迎登录 Trove 管理平台
        </Title>
        <Text style={{
          color: 'rgba(255,255,255,0.8)',
          fontSize: '16px',
          textAlign: 'center',
          lineHeight: '1.6',
        }}>
          或许我们只是星辰大海的点点
        </Text>
      </div>

      {/* 右侧登录表单 */}
      <div className="login-right" style={{
        flex: '0 0 auto',
        width: '480px',
        maxWidth: '480px',
        padding: '40px',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        minHeight: '100vh',
        animation: 'fadeInRight 1s ease-out',
      }}>
        <Card
          className="glass-card"
          style={{
            width: '100%',
            maxWidth: '400px',
            background: 'rgba(255, 255, 255, 0.95)',
            backdropFilter: 'blur(20px)',
            border: '1px solid rgba(255, 255, 255, 0.2)',
            borderRadius: '20px',
            boxShadow: '0 20px 40px rgba(0, 0, 0, 0.1)',
            padding: '30px',
            animation: 'fadeInUp 1s ease-out 0.3s both',
          }}
        >
          <div style={{ textAlign: 'center', marginBottom: '32px' }}>
            <div className="icon-pulse" style={{
              width: '60px',
              height: '60px',
              background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
              borderRadius: '50%',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              margin: '0 auto 16px',
              boxShadow: '0 8px 16px rgba(102, 126, 234, 0.3)',
            }}>
              <UserOutlined style={{ fontSize: '24px', color: 'white' }} />
            </div>
            <Title level={3} className="gradient-text" style={{ marginBottom: '8px', color: '#333' }}>
              Trove 管理平台
            </Title>
            <Text type="secondary">
              账号密码登录
            </Text>
          </div>

          <Form
            form={form}
            name="login"
            onFinish={handleLogin}
            autoComplete="off"
            size="large"
            initialValues={{
              username: 'admin',
              password: 'admin123',
              remember: true,
            }}
          >
            <Form.Item
              name="username"
              rules={[
                { required: true, message: '请输入用户名' },
                { min: 3, message: '用户名至少3个字符' },
              ]}
            >
              <Input
                prefix={<UserOutlined style={{ color: '#667eea' }} />}
                placeholder="用户名"
                autoComplete="username"
                style={{
                  borderRadius: '12px',
                  border: '2px solid #f0f0f0',
                  padding: '12px 16px',
                  fontSize: '16px',
                }}
              />
            </Form.Item>

            <Form.Item
              name="password"
              rules={[
                { required: true, message: '请输入密码' },
                { min: 6, message: '密码至少6个字符' },
              ]}
            >
              <Input.Password
                prefix={<LockOutlined style={{ color: '#667eea' }} />}
                placeholder="密码"
                autoComplete="current-password"
                style={{
                  borderRadius: '12px',
                  border: '2px solid #f0f0f0',
                  padding: '12px 16px',
                  fontSize: '16px',
                }}
              />
            </Form.Item>

            {/* 验证码输入框 - 登录失败2次后显示 */}
            {showCaptcha && (
              <Form.Item
                name="captcha"
                rules={[
                  { required: true, message: '请输入验证码' },
                  { len: 4, message: '验证码为4位字符' },
                ]}
              >
                <Row gutter={8}>
                  <Col span={14}>
                    <Input
                      prefix={<SafetyOutlined style={{ color: '#667eea' }} />}
                      placeholder="验证码"
                      maxLength={4}
                      style={{
                        borderRadius: '12px',
                        border: '2px solid #f0f0f0',
                        padding: '12px 16px',
                        fontSize: '16px',
                      }}
                    />
                  </Col>
                  <Col span={10}>
                    <Captcha
                      width={100}
                      height={40}
                      length={4}
                      onChange={setCaptchaCode}
                    />
                  </Col>
                </Row>
              </Form.Item>
            )}

            <Form.Item>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <Form.Item name="remember" valuePropName="checked" noStyle>
                  <Checkbox style={{ color: '#666' }}>记住我</Checkbox>
                </Form.Item>
                <Button type="link" style={{ padding: 0, color: '#667eea' }}>
                  忘记密码？
                </Button>
              </div>
            </Form.Item>

            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                loading={loginLoading}
                block
                className="login-button"
                icon={loginLoading ? <LoadingOutlined /> : undefined}
                style={{
                  height: '50px',
                  borderRadius: '12px',
                  fontSize: '16px',
                  fontWeight: 'bold',
                  background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                  border: 'none',
                  boxShadow: '0 4px 12px rgba(102, 126, 234, 0.4)',
                  transition: 'all 0.3s ease',
                }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.transform = 'translateY(-2px)';
                  e.currentTarget.style.boxShadow = '0 6px 16px rgba(102, 126, 234, 0.5)';
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.transform = 'translateY(0)';
                  e.currentTarget.style.boxShadow = '0 4px 12px rgba(102, 126, 234, 0.4)';
                }}
              >
                {loginLoading ? '登录中...' : '登录'}
              </Button>
            </Form.Item>
          </Form>

          <div style={{
            textAlign: 'center',
            marginTop: '24px',
            padding: '16px',
            background: 'rgba(102, 126, 234, 0.05)',
            borderRadius: '12px',
            border: '1px solid rgba(102, 126, 234, 0.1)',
          }}>
            <Text style={{ color: '#667eea', fontSize: '14px', fontWeight: '500' }}>
              测试账户: admin / admin123
            </Text>
          </div>
        </Card>
      </div>

      {/* 底部版权信息 */}
      <div style={{
        position: 'absolute',
        bottom: '20px',
        left: '50%',
        transform: 'translateX(-50%)',
        color: 'rgba(255, 255, 255, 0.7)',
        fontSize: '14px',
        textAlign: 'center',
      }}>
        <Text style={{ color: 'rgba(255, 255, 255, 0.7)' }}>
          版权所有 © 蜀ICP备2020022644号-1
        </Text>
      </div>
    </div>
  );
};

export default Login;
